/* eslint-disable */
const JSZip = require('jszip');
const path = require('path');
const RawSource = require('webpack-sources').RawSource;

const zip = new JSZip();

module.exports = class ZipPlugin {
  constructor(options) {
    this.options = options;
  }

  apply(compiler) {
    compiler.hooks.emit.tapAsync('ZipPlugin', (compilation, callback) => {
      const folder = zip.folder(this.options.filename);
      for (const filename in compilation.assets) {
         const source = compilation.assets[filename].source();
         folder.file(filename, source);
      }
      zip.generateAsync({
        // 指定生成的内容类型
        type: 'nodebuffer',
      }).then((content) => {
        // 拼接webpack配置的output属性和传入的文件名生成输出路径
        // const outputPath = path.join(compiler.options.output.path, this.options.filename + '.zip');
        // 生成相对路径
        // const outputRelativePath = path.relative(compilation.options.output.path, outputPath);
        compilation.assets[this.options.filename + '.zip'] = new RawSource(content);
        // callback一定要调用，否则不会生成文件。通知webpack异步任务已完成。
        callback();
      })
    });
  }
};